package com.example.myapplication;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity1 extends AppCompatActivity {

    private EditText etHeight, etWeight;
    private TextView tvResult, tvAdvice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        etHeight = findViewById(R.id.etHeight);
        etWeight = findViewById(R.id.etWeight);
        Button btnCalculate = findViewById(R.id.btnCalculate);
        tvResult = findViewById(R.id.tvResult);
        tvAdvice = findViewById(R.id.tvAdvice);

        btnCalculate.setOnClickListener(v -> calculateBMI());
    }

    private void calculateBMI() {
        String heightStr = etHeight.getText().toString();
        String weightStr = etWeight.getText().toString();

        if (heightStr.isEmpty() || weightStr.isEmpty()) {
            tvResult.setText("请输入完整数据");
            tvAdvice.setText("");
            return;
        }

        try {
            double height = Double.parseDouble(heightStr) / 100;
            double weight = Double.parseDouble(weightStr);

            if (height <= 0 || weight <= 0) {
                tvResult.setText("数据必须大于0");
                return;
            }

            double bmi = weight / (height * height);
            String bmiFormatted = String.format("%.2f", bmi);
            String advice = getHealthAdvice(bmi);

            tvResult.setText("BMI值: " + bmiFormatted);
            tvAdvice.setText(advice);

        } catch (NumberFormatException e) {
            tvResult.setText("请输入有效数字");
            tvAdvice.setText("");
        }
    }

    private String getHealthAdvice(double bmi) {
        if (bmi < 18.5) {
            return "体重过轻，注意营养补充";
        } else if (bmi < 24) {
            return "体重正常，继续保持！";
        } else if (bmi < 28) {
            return "超重，建议适当运动";
        } else {
            return "肥胖，请咨询专业医师";
        }
    }
}
